package com.hao.redis.client;

import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;

public class JedisClient {

	private static Logger logger = Logger.getLogger(JedisClient.class);

	private final static int TIME_OUT = 500;
	
	public final static String SUCCESS_FLAG = "OK";

	private JedisPool pool;

	private static JedisClient jedisClinet = new JedisClient();

	public static JedisClient getInstance() {
		return jedisClinet;
	}

	private JedisClient() {
		
	}

	public void init() {
		if (pool != null){
			return;
		}
		try {
			logger.info("init jedis config.");
			
			String server = "10.10.64.48";
			int port = 6379;
			int maxActive = 200;
			int maxIdle = 40;
			int maxWait = 200;

			JedisPoolConfig poolConfig = new JedisPoolConfig();
			poolConfig.setMaxActive(maxActive);
			poolConfig.setMaxIdle(maxIdle);
			poolConfig.setMaxWait(maxWait);
			pool = new JedisPool(poolConfig, server, port, TIME_OUT);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	public Jedis getJedis() {
		Jedis jedis = null;
		if (pool != null) {
			try {
				jedis = pool.getResource();
			} catch (JedisConnectionException e) {
				logger.error("从redis获取数据超时.", e);
				if (jedis != null) {
					pool.returnBrokenResource(jedis);
					jedis = null;
				}
				try {
					logger.info("再次连接redis获取数据");
					jedis = pool.getResource();
				} catch (JedisConnectionException e1) {
					logger.error("再次从redis获取数据超时.", e);
					if (jedis != null) {
						pool.returnBrokenResource(jedis);
						jedis = null;
					}
				}
			}

		}
		return jedis;
	}

	public void returnResource(Jedis jedis) {
		if (pool != null && jedis != null) {
			pool.returnResource(jedis);
		}
	}
	public void returnBrokenResource(Jedis jedis) {
		if (pool != null && jedis != null) {
			pool.returnBrokenResource(jedis);
		}
	}
	
	public void destroy(){
		if (pool != null ) {
			pool.destroy();
		}
	}
}
